const mongoose=require('mongoose');
const Cate=require('../models/cate.model');

//创建
exports.create=function(req, res, next) {
    /* var famarr=req.body.familay.split('，');
    for(var i=0;i<famarr.length;i+=2){
        req.body.familay['123']=famarr[i+1];
        req.body.familay['456']=famarr[i+1];
       req.body.familay[famarr[i]]=famarr[i+1];
    } 
    console.log(req.body); */
    console.log(req.body);
    const cate = new Cate(req.body);
    //console.log(cate);
    cate.save().then(data => {
        res.json(data);
    });
};
//修改
exports.update = function(req, res, next) {
    var id = req.params.id;
    console.log(req.params);
    console.log(req.body);
    Cate.findByIdAndUpdate(id,{$set:req.body},{new:false})
    .then(data=>{
        res.json(data);//修改之前的数据
    })
};
//获取
exports.get=function(req, res, next) {
    var id=req.params.id;
    Cate.findById(id).then(data=>{
        res.json(data);
        //console.log(data);
    })
};
//删除
exports.remove=function(req, res, next) {
    //console.log(req.body);
    var id = req.params.id;
    //console.log(cate);
    Cate.findByIdAndDelete(id).then(data=>{
        res.json(data);
    })
};
//查询全部

function reservTree(data,pid){
    var result=[];
    var temp;

    var data=JSON.parse(JSON.stringify(data));//
    for(var i in data){
        if(data[i].parentId == pid){
            result.push(data[i]);
            temp = reservTree(data,data[i]._id);
            if(temp.length > 0){
                data[i].children=temp;
            }
        }
    }
    return result;

};
exports.list=function(req, res, next) {
    var type=req.params.type;
    Cate.find({type:type}).then(data=>{
        res.json(reservTree(data,null));
    })
};